#!/usr/bin/perl
# ISI DARI STORE-ID DIBAWAH INI DARI SHUDY
# SHUDYLAH BERBAGI ILMU :3
# ucok_karnadi(at)yahoo.com or https://twitter.com/syaifuddin_jw

# for ALL Youtube ( range & non range )
# first you need do this
# install package dependencies "apt-get install libfile-readbackwards-perl"
# add line below to your squid config and remove "#"
     
# strip_query_terms off
# acl yutub dstdomain .youtube.com .youtu.be
# logformat squid1 %{Referer}>h %ru
# access_log /var/log/squid/yt.log squid1 yutub
# acl redirec urlpath_regex -i &redirect_counter=1&cms_redirect=yes &ir=1&rr=12
# cache deny redirec
# storeurl_access deny redirec

use IO::File;
STDOUT->autoflush(1);
$debug=1;

my $logfile = '/var/log/squid3/storeurl.log';

open my $logfh, '>>', $logfile
    or die "Couldn't open $logfile for appending: $!\n" if $debug;
$logfh->autoflush(1) if $debug;

$|=1;
while (<>) {
chop;
@X = split;
print $logfh "in : @X \n" if ($debug>=1);

if ( $X[0] =~ m/^http\:\/\/.*/) {
$x = $X[0]
$_ = $X[0];
$u = $X[0];
} else {
$x = $X[1]
$_ = $X[1];
$u = $X[1];
}

if ($x =~ m/^http\:\/\/.*(youtube|google).*videoplayback.*/){
        @itag = m/[&?](itag=[0-9]*)/;
        @IDS = m/[&?]id\=([a-zA-Z0-9\-\_]*)/;
        @CPN = m/[&?]cpn\=([a-zA-Z0-9\-\_]*)/;
        $id = &GetID($CPN[0], $IDS[0]);
        @range = m/[&?](range=[^\&\s]*)/;
        $out="http://video-srv.youtube.com.squid.internal/id=" . $id . "&@itag@range";

} elsif ($x =~ m/^http\:\/\/.*(profile|photo|creative).*\.ak\.fbcdn\.net\/((h|)(profile|photos)-ak-)(snc|ash|prn)[0-9]?(.*)/) {
        $out="http://fbcdn.net.squid.internal/" . $2  . "fb" .  $6  ;

} elsif ($x =~ m/^http:\/\/i[1-4]\.ytimg\.com\/(.*)/) {
        $out="http://ytimg.com.squid.internal/" . $1 ;

} elsif ($x =~ m/^http:\/\/.*\.dl\.sourceforge\.net\/(.*)/) {
          $out="http://dl.sourceforge.net.squid.internal/" . $1 ;

} else {
        $out=$x;

}
if ( $X[0] =~ m/^http\:\/\/.*/) {
 print $logfh "out: OK store-id=$out\n" if ($debug>=1);
 print "OK store-id=$out\n" ;
} else {
 print $logfh "out: $X[0] OK store-id=$out\n" if ($debug>=1);
 print $X[0] . " OK store-id=$out\n" ;
}
}


sub GetID
{
$id = "";
use File::ReadBackwards;
my $lim = 100 ;
my $ref_log = File::ReadBackwards->new('/var/log/squid3/yt.log');
while (defined($line = $ref_log->readline))
{
if ($line =~ m/.*youtube.*\/(watch\?.*v=|embed\/)([a-zA-Z0-9\-\_]*).*\s.*id=$IDS[0].*/){
$id = $2;
last;
}
if ($line =~ m/.*youtube.*\/.*cpn=$CPN[0].*[&](video_id|docid|v)=([a-zA-Z0-9\-\_]*).*/){
$id = $2;
last;
}
if ($line =~ m/.*youtube.*\/.*[&?](video_id|docid|v)=([a-zA-Z0-9\-\_]*).*cpn=$CPN[0].*/){
$id = $2;
last;
}
last if --$lim <= 0;
}
if ($id eq ""){
$id = $IDS[0];
}
$ref_log->close();
return $id;
}

